Ini Files


Application settings and premenent variables are always stored in text files. It
is the easiest way. Text files lack the ability of direct access, instead you have
to read all the lines to access certain information. Also it is very hard in modification,
for example if you want to insert a line in a text file, you should create temporary
file and copy all data to it.

Delphi and Windows provides a very good and easy technique to store such configuration
and setting data. It is the INI files.
Ini files is text files, but it is very organized, it is consists of
sections, each
sections contains a
identifiers and values. You can access any section, and identifier
directly without wory about the preceding and subsequent data lines.

Example of Ini file structure:

[windows]
load=
run=
NullPort=None
BaseCodePage=1256
BaseCodePage=1256

[Desktop]
Wallpaper=C:\WINDOWS\SETUP.BMP
TileWallpaper=0
WallpaperStyle=0

[Intl]
iCountry=966
ICurrDigits=2
iCurrency=2
iDate=1

Example of section names: [Windows], [Desktop].
Example of identifiers (Variables) :
run, load, iDate
Example of values: 966, 2, C:\WINDOWS\SETUP.BMP

Writing data to Ini file example:

var
Ini:
TIniFile;
begin
Ini:= TIniFile.Create(
'settings.ini');
Ini.
WriteString('Form', 'caption', Form1.Caption);
Ini.WriteInteger('Form', 'left', Form1.Left);
Ini.WriteInteger('Form', 'top', Form1.Top);
Ini.WriteInteger('Form', 'width', Form1.Width);
Ini.WriteInteger('Form', 'height', Form1.Height);
Ini.Free;
end;

Reading data from Ini file example:

var
Ini: TIniFile;
begin
Ini:= TIniFile.Create('settings.ini');
Form1.Caption:= Ini.
ReadString('Form', 'caption', Form1.Caption);
Form1.Left:= Ini.ReadInteger('Form', 'left', Form1.Left);
Form1.Top:= Ini.ReadInteger('Form', 'top', Form1.Top);
Form1.Width:= Ini.ReadInteger('Form', 'width', Form1.Width);
Form1.Height:= Ini.ReadInteger('Form', 'height', Form1.Height);
Ini.Free;
end;


Notes:

-
TIniFile class exists in IniFiles unit, so that you need to add IniFiles to your
uses clause.
- In Reading values, you can assign a default value in case of the value, section,
or the ini file does not exist, example:

Speed:= Ini.ReadString('car', 'speed',
220);.

In this case if '
speed' does not assigned yet, then 220 will be returned.
- Not like Windows Registry, which it is a centralized database, INI files can be
stored in any directory, such as applications working directory, so that it is suitable
when you want to have multiple executables for the same version of your application
in different directories to have different settings.

See also

Registry